package com.rockcent.wechat.controller;

import com.rockcent.common.common.JsonResult;
import com.rockcent.common.common.PageResult;
import com.rockcent.common.common.RestDoing;
import com.rockcent.common.controller.BaseController;
import com.rockcent.common.domain.enumclass.Whether;
import com.rockcent.common.utils.RBeanUtils;
import com.rockcent.mall.lib.domain.*;
import com.rockcent.mall.lib.domain.enumclass.*;
import com.rockcent.mall.lib.dto.*;
import com.rockcent.mall.lib.repository.*;
import com.rockcent.service.MallService;
import com.rockcent.wechat.Routes;
import com.rockcent.wechat.helper.CustomerHelper;
import org.apache.commons.lang3.EnumUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * Created by zhangjh on 2016/9/30.
 */
@RestController
@RequestMapping(value = Routes.API_PREFIX)
public class MallController extends BaseController {
    private static final Logger log = LoggerFactory.getLogger(MallController.class);

    @Autowired
    CustomerCouponWalletRepository customerCouponWalletRepository;
    @Autowired
    MerchantRepository merchantRepository;
    @Autowired
    MerchantCouponRepository merchantCouponRepository;
    @Autowired
    RecommendRepository recommendRepository;
    @Autowired
    private MerchantProductRepository merchantProductRepository;
    @Autowired
    private CategoryRepository categoryRepository;
    @Autowired
    private MallRepository mallRepository;
    @Autowired
    private BannerRepository bannerRepository;
    @Autowired
    private WechatConfigRepository wechatConfigRepository;
    @Autowired
    private CustomerHelper customerHelper;

    @Autowired
    private MerchantProductStatisticsRepository merchantProductStatisticsRepository;
    @Autowired
    private FavoriteRepository favoriteRepository;
    @Autowired
    private TemplateRepository templateRepository;
    @Autowired
    private TopicRepository topicRepository;
    @Autowired
    private MallProtocolRepository mallProtocolRepository;

    @Autowired
    private MallService mallService;
    /**
     * @api {get} /api/v2/mall/coupon_center 领券中心
     * @apiGroup mall
     * @apiVersion 1.0.0
     * @apiParam {Integer} pageNo 页码
     * @apiParam {Integer} pageSize 每页记录数
     * @apiParam {String} couponType NEW("最新"),VOUCHERS("抵用券"), DISCOUNT("折扣券")
     *
     * @apiSuccess {Long} id 券ID
     * @apiSuccess {Date} dateCreated 创建时间
     * @apiSuccess {Date} lastUpdated 更新时间
     * @apiSuccess {Long} version 版本
     * @apiSuccess {String} type 类型 VOUCHERS("抵用券"), DISCOUNT("折扣券")
     * @apiSuccess {String} name 名称
     * @apiSuccess {String} barCode 唯一编号
     * @apiSuccess {BigDecimal} faceValue 面值(抵用券)
     * @apiSuccess {BigDecimal} discount 享受折扣(折扣券)
     * @apiSuccess {BigDecimal} limitAmount 最低消费金额
     * @apiSuccess {Long} quantity 剩余数量
     * @apiSuccess {Date} dateEnabled 有效期开始时间
     * @apiSuccess {Date} dateDisabled 有效期结束时间
     * @apiSuccess {String} useScope 适用范围 ALL_STORE("所有门店"), ALL_PRODUCT("所有产品"), PART_STORE("指定门店"), PART_PRODUCT("指定产品")
     * @apiSuccess {Date} dateIssued 发放时间
     * @apiSuccess {String} drawLimit 领取限制 NO("没有上限"), ALL("总共上限"), DAYS("每天上限")
     * @apiSuccess {Long} limitCount 限制数量
     * @apiSuccess {String} sharing 是否共享 YES("是"), NO("否")
     * @apiSuccess {String} showOnCenter 是否发布到领券中心 YES("是"), NO("否")
     * @apiSuccess {String} showOnMerchant 是否发布到店铺首页 YES("是"), NO("否")
     * @apiSuccess {String} logoUrl LOGO图
     * @apiSuccess {String} introduction 使用说明
     * @apiSuccess {String} status 状态 WAIT_ISSUE("待发放"), ISSUED("已发放"), SOLDOUT("已下架"), EXPIRED("已过期"), DELETED("已删除")
     * @apiSuccess {Long} merchantId 商家ID
     * @apiSuccess {String} merchantName 商铺名称
     * @apiSuccess {Integer} leaveTotal 发放数量
     * @apiSuccess {Boolean} hadToke 用户是否已经领取
     *
     * @apiSuccessExample {json} Success-Response:
     *{
     *  "code": "1",
     *  "desc": "成功",
     *  "data": {
     *          "data": [
     *                      {
     *                          "id": 26,
     *                          "dateCreated": "2016-07-19 13:50:37",
     *                          "lastUpdated": "2016-08-08 17:43:09",
     *                          "type": "VOUCHERS",
     *                          "name": "testCM",
     *                          "faceValue": 2,
     *                          "limitAmount": 11,
     *                          "quantity": 110,
     *                          "dateEnabled": "2016-07-19 00:00:00",
     *                          "dateDisabled": "2017-07-19 00:00:00",
     *                          "useScope": "PART_PRODUCT",
     *                          "dateIssued": "2016-07-19 13:49:00",
     *                          "drawLimit": "NO",
     *                          "sharing": "YES",
     *                          "showOnCenter": "YES",
     *                          "showOnMerchant": "NO",
     *                          "logoUrl": "/20160719/20160719135021rMkW4wCG.png",
     *                          "introduction": "11",
     *                          "status": "ISSUED",
     *                          "merchantId": 2,
     *                          "merchantName": "b1测试商户 X",
     *                          "leaveTotal": 110,
     *                          "verifiedCount": 0,
     *                          "productList": [],
     *                          "hadToken": false,
     *                          "storeList": []
     *                      },
     *                          ...
     *                  ],
     *              "totalCount": 2,
     *              "totalPage": 1,
     *              "pageNo": 0,
     *              "pageSize": 10
     *          }
     *  }
     */
    @RequestMapping(value = Routes.MALL_COUPON_CENTER, method = RequestMethod.GET)
    @ResponseBody
    public JsonResult couponCenter(String couponType ,Integer pageNo,Integer pageSize,HttpServletRequest request) {
        RestDoing doing = jr -> {
            if (pageNo == null && pageSize == null) {
                jr.remind("请输入分页条件",log);
                return;
            }
            if (couponType == null) {
                jr.remind("couponType is null",log);
                return;
            }
            if (!EnumUtils.isValidEnum(CouponType.class, couponType) && !"NEW".equals(couponType)) {
                jr.errorParam("couponType is illegal",log);
                return;
            }
            //用户可以在未登录情况下访问领券中心
            CustomerDto customerDto = customerHelper.getSession(request);
            List<Long> customerCouponList1 = null;
            if (customerDto.getId() != null) {
                //用户已从领券中心领取的券
                List<CustomerCouponWallet> customerCouponWalletList = customerCouponWalletRepository.findByCustomerId(customerDto.getId());
                customerCouponList1 = customerCouponWalletList.stream().map(CustomerCouponWallet::getCouponId).collect(Collectors.toList());
            }
            //lambda表达式的需要，不能传变化的值
            List<Long> customerCouponList = customerCouponList1;

            PageResult<MerchantCoupon> pageResult = merchantCouponRepository.findByShowOnCenterAndStatusAndMallId(Whether.YES, couponType, MerchantCouponStatus.ISSUED, customerDto.getMallId(), this.getPage(pageNo, pageSize));
            List<Long> merchantIdList = pageResult.data.stream().map(MerchantCoupon::getMerchantId).collect(Collectors.toList());
            List<Merchant> merchantList = merchantRepository.findByIdIn(merchantIdList);
            Map<Long, List<Merchant>> map = merchantList.stream().collect(Collectors.groupingBy(Merchant::getId));
            List merchantCouponDtoList = pageResult.data.stream().map(merchantCoupon -> {
                MerchantCouponDto merchantCouponDto = new MerchantCouponDto();
                RBeanUtils.copyProperties(merchantCoupon, merchantCouponDto);
                //枚举类型数据
                merchantCouponDto.setType(merchantCoupon.getType().toString());
                merchantCouponDto.setLimitAmount(merchantCoupon.getLimitAmount().doubleValue());
                merchantCouponDto.setDateDisabled(merchantCoupon.getDateDisabled());
                merchantCouponDto.setDateEnabled(merchantCoupon.getDateEnabled());
                merchantCouponDto.setUseScope(merchantCoupon.getUseScope().toString());
                merchantCouponDto.setDrawLimit(merchantCoupon.getDrawLimit().toString());
                merchantCouponDto.setSharing(merchantCoupon.getSharing().toString());
                merchantCouponDto.setShowOnCenter(merchantCoupon.getShowOnCenter().toString());
                merchantCouponDto.setShowOnMerchant(merchantCoupon.getShowOnMerchant().toString());
                merchantCouponDto.setStatus(merchantCoupon.getStatus().toString());
                //设置商铺名称
                if (map != null && map.get(merchantCoupon.getMerchantId()).get(0) != null) {
                    merchantCouponDto.setMerchantName(map.get(merchantCoupon.getMerchantId()).get(0).getName());
                }
                //设置是否已领取券
                if (customerCouponList != null && customerCouponList.contains(merchantCoupon.getId())) {
                    merchantCouponDto.setHadToken(true);
                }
                return merchantCouponDto;
            }).collect(Collectors.toList());
            pageResult.data = merchantCouponDtoList;
            jr.setData(pageResult);
        };
        return doing.go(request, log);
    }

    /**
     * @api {get} /api/v2/mall/preference 优选(商户下没商品的不显示商户)
     * @apiGroup mall
     * @apiVersion 1.0.0
     *
     * @apiHeader {String} userToken 用户token
     * @apiHeader {String} domain 平台域名
     *
     * @apiSuccess {Long} merchantId 商铺ID
     * @apiSuccess {String} merchantName 商铺名称
     * @apiSuccess {String} logoUrl 商铺logoUrl
     * @apiSuccess {Boolean} taken 是否关注
     * @apiSuccess {List} productList 产品列表
     * @apiSuccess {Date} dateCreated 创建时间
     * @apiSuccess {Date} lastUpdated 更新时间
     * @apiSuccess {Long} version 版本
     * @apiSuccess {String} identifier 产品唯一的识别码
     * @apiSuccess {String} name 名称
     * @apiSuccess {String} type 类型 ALL("全部"), GOODS("商品"), SERVICE("服务")
     * @apiSuccess {BigDecimal} basePrice 原价
     * @apiSuccess {BigDecimal} sellPrice 售价
     * @apiSuccess {Long} quantity 库存数量
     * @apiSuccess {BigDecimal} carriage 运费
     * @apiSuccess {Boolean} refundable 是否支持过期退
     * @apiSuccess {Boolean} sellnow 是否立即开售
     * @apiSuccess {Date} dateSelling 开售时间
     * @apiSuccess {Long} limitCount 限购数量
     * @apiSuccess {String} logoUrl LOGO图
     * @apiSuccess {String} note 卖点介绍
     * @apiSuccess {String} status 状态 SELLING("在售"), SUPPLIER_CANCEL_SOLDOUT("分销市场 供应商取消供货 已下架"),DISTRIBUTOR_CANCEL_SOLDOUT("分销市场 分销商取消代销 已下架"), SOLDOUT("已下架"), EXPIRED("已过期"), DELETED("已删除"), WAIT_APPLY("待申请"), WAIT_AUDIT("待审核"), AUDIT_PASS("审核通过"), AUDIT_FAIL("审核不通过")
     * @apiSuccess {Long} mallId 平台 id
     * @apiSuccess {Long} merchantId 商家 id
     * @apiSuccess {String} serveRate 服务费比率
     * @apiSuccess {String} shippingType 支持的物流类型 SHOP_PICKUP("到店自取"), SHIPPING("物流"), SHOP_PICKUP_AND_SHIPPING("物流及到店自取")
     * @apiSuccess {BigDecimal} resellFee 分销佣金
     * @apiSuccess {BigDecimal} shareFee 分享返利
     * @apiSuccess {Boolean} recommend 是否在分销市场展示
     *
     * @apiSuccessExample {json} Success-Response:
     * {
     *  "code": "1",
     *  "desc": "成功",
     *  "data": [
     *              {
     *                  "merchantId": 1,
     *                  "merchantName": "秋甜商城",
     *                  "logoUrl": "http://uploads.rockcent.com//dev/merchant/logo/201610/281843534568a846f1b-e148-4bce-8ea6-9c5f694ea68bgrinchtocat.gif",
     *                  "taken": false,
     *                  "productList": [
     *                                  {
     *                                      "id": 131,
     *                                      "dateCreated": "2016-07-31 17:25:02",
     *                                      "lastUpdated": "2016-08-04 14:20:22",
     *                                      "version": 4,
     *                                      "identifier": "8350940b25b25e8efd020d49a14845d5",
     *                                      "name": "阿斯顿",
     *                                      "type": "GOODS",
     *                                      "basePrice": 123,
     *                                      "sellPrice": 100,
     *                                      "quantity": 98,
     *                                      "carriage": 0,
     *                                      "refundable": false,
     *                                      "sellnow": true,
     *                                      "dateSelling": 1469957101000,
     *                                      "limitCount": 0,
     *                                      "logoUrl": "/20160731/201607311724500CwK5WyA.jpg",
     *                                      "note": "123",
     *                                      "status": "SELLING",
     *                                      "mallId": 1,
     *                                      "merchantId": 1,
     *                                      "serveRate": "24",
     *                                      "shippingType": "SHIPPING",
     *                                      "resellFee": 12,
     *                                      "shareFee": 11,
     *                                      "recommend": false
     *                                  },
     *                                  ...
     *                              ]
     *              }，
     *              ...
     *      ]
     *  }
     */
    @RequestMapping(value = Routes.MALL_PREFERENCE, method = RequestMethod.GET)
    @ResponseBody
    public JsonResult advisingMerchant( HttpServletRequest request) {
        CustomerDto customerDto = customerHelper.getSession(request);
        RestDoing doing = jr -> {
            //取本平台下的推荐商家,取5个
            List<Recommend> recommendList = recommendRepository.findByMallIdAndIsDelete(customerDto.getMallId(), Whether.NO).stream().limit(5).collect(Collectors.toList());
            List<RecommendDto> recommendDtoList = recommendList.stream().map(recommend -> {
                RecommendDto recommendDto = new RecommendDto();
                //设置商户信息
                Merchant merchant = merchantRepository.findOne(recommend.getMerchantId());
                recommendDto.setMerchantId(merchant.getId());
                recommendDto.setTitle(recommend.getTitle());
                recommendDto.setMerchantName(merchant.getName());
                recommendDto.setLogoUrl(merchant.getLogoUrl());
                //用户是否有关注该商铺
                Favorite favorite = favoriteRepository.findByCustomerIdAndMerchantIdAndType(customerDto.getId(), recommend.getMerchantId(), FavoriteType.MERCHANT);
                if (favorite != null) {
                    recommendDto.setTaken(true);
                }
                /**
                 * 获取商铺销量前20的商品ID
                 */
                List<ProductStatistics> productStatisticsList = merchantProductStatisticsRepository.getTopSale20(recommend.getMerchantId(), customerDto.getMallId());
                //产品ID
                List<Long> productIdList = productStatisticsList.stream().map(ProductStatistics::getProductId).collect(Collectors.toList());
                List<Product> productList = merchantProductRepository.findByIdInAndStatus(productIdList, ProductStatus.SELLING);
                if (productList == null || productList.size() <= 0) {
                    //如果商铺下没有商品，删掉该商铺
                    recommendDto = null;
                } else {
                    //该商户的产品
                    recommendDto.setProductList(productList);
                }
                return recommendDto;
            }).filter(recommendDto -> recommendDto != null).collect(Collectors.toList());

            jr.setData(recommendDtoList);
        };
        return doing.go(request, log);
    }

    /**
     *
     * @api {get} /api/v2/mall/layout 首页布局
     * @apiGroup mall
     * @apiVersion 1.0.0
     *
     * @apiParam {Long} mallId
     *
     * @apiSuccess {String} templates 模板类型
     * @apiSuccess {String} name 模板名
     * @apiSuccess {String} items 模板内子项
     * @apiSuccess {String} templates 模板内子项序号
     *
     * @apiSuccessExample {json} Success-Response:
     * {
     *  "code": "1",
     *  "desc": "成功",
     *  "data": [
     *              {
     *                  "id": 5,
     *                  "dateCreated": "2016-11-23 19:45:03",
     *                  "lastUpdated": "2016-11-24 15:06:26",
     *                  "version": 2,
     *                  "mallId": 1,
     *                  "title": "歌力思",
     *                  "type": "TYPE_FOURTH",
     *                  "content": "[{\"pic_path\":\"http://uploads.rockcent.com//uat/product/face/201611/2415441203ce799f8d-5037-4409-8f95-835dd35a47d0屏幕快照 2016-11-22 下午3.41.36.png\",\"type\":\"0\",\"url\":\"http://www.baidu.com\"},{\"pic_path\":\"http://uploads.rockcent.com//uat/product/face/201611/2415456808661f69a4-94d2-4b0f-8efe-64bb017509cd屏幕快照 2016-11-22 下午3.37.15.png\",\"type\":\"0\",\"url\":\"http://www.baidu.com\"},{\"pic_path\":\"http://uploads.rockcent.com//uat/product/face/201611/2415518501b45f2a5c-19fc-49f9-8155-f489cd1e34a6屏幕快照 2016-11-22 下午3.37.07.png\",\"type\":\"0\",\"url\":\"http://www.baidu.com\"},{\"pic_path\":\"http://uploads.rockcent.com//uat/product/face/201611/24155267300fd94b4d-3cf8-40c1-8ab9-46d8af169836屏幕快照 2016-11-22 下午3.39.17.png\",\"type\":\"0\",\"url\":\"http://www.baidu.com\"}]",
     *                  "seqNo": 5
     *              },
     *              ...
     *     ]
     *  }
     */
    @RequestMapping(value = Routes.MALL_LAYOUT, method = RequestMethod.GET)
    @ResponseBody
    public JsonResult layout(HttpServletRequest request) {
        CustomerDto customerDto = customerHelper.getSession(request);
        RestDoing doing = jr -> {
            List<Template> templateList = templateRepository.findByMallIdAndIsDeleteOrderBySeqNoAsc(customerDto.getMallId(),Whether.NO);
            jr.setData(templateList);
        };
        return doing.go(request, log);
    }

    /**
     *
     * @api {get} /api/v2/mall/list_banners 广告管理列表
     * @apiGroup mall
     * @apiVersion 1.0.0
     *
     * @apiParam {Long} mallId 平台ID
     *
     * @apiSuccess {Long} id 广告ID
     * @apiSuccess {Date} dateCreated 创建时间
     * @apiSuccess {Date} lastUpdated 更新时间
     * @apiSuccess {Long} mallId 平台ID
     * @apiSuccess {String} picPath 图片路径
     * @apiSuccess {Integer} seqNo 序号（排序字段）
     * @apiSuccess {String} title 标题
     * @apiSuccess {String} url 链接
     *
     * @apiSuccessExample {json} Success-Response:
     * {
     *  "code": "1",
     *  "desc": "成功",
     *  "data": [
     *      {
     *          "id": 1,
     *          "dateCreated": "2016-10-14 13:23:14",
     *          "lastUpdated": "2016-10-14 13:23:17",
     *          "version": 0,
     *          "mallId": 1,
     *          "picPath": "http://upload.dev.rockcent.com/images/20160506/20160506193437xjzaTbmd.jpg",
     *          "seqNo": 0,
     *          "title": ""
     *          "url": "http://upload.dev.rockcent.com/images/20160506/20160506193437xjzaTbmd.jpg"
     *       },
     *          ...
     *     ]
     *  }
     *
     */
    @RequestMapping(value = Routes.MALL_LIST_BANNERS, method = RequestMethod.GET)
    @ResponseBody
    public JsonResult listBanners(Long mallId, HttpServletRequest request) {
        RestDoing doing = jr -> {
            if (null == mallId) {
                jr.remind("mallId:" + Mall.CHECK_ID_IS_NOT_NULL,log);
                return;
            }
            if (!mallRepository.exists(mallId)) {
                jr.errorParam("mallId:" + Mall.REMIND_RECORD_IS_NOT_EXIST,log);
            }
            List<Banner> bannerList = bannerRepository.findByMallIdAndIsDeleteOrderBySeqNoAsc(mallId, Whether.NO);
            jr.setData(bannerList);
        };
        return doing.go(request, log);
    }

    /**
     *
     * @api {get} /api/v2/mall/list_themes 专题列表
     * @apiGroup mall
     * @apiVersion 1.0.0
     *
     * @apiParam {Integer} pageNo 页码
     * @apiParam {Integer} pageSize 页记录数
     * @apiParam {Integer} [id] 专题ID，传该值时，查该id的专题，
     *
     * @apiSuccess {Long} id ID
     * @apiSuccess {Date} dateCreated 创建时间
     * @apiSuccess {Date} lastUpdated 更新时间
     * @apiSuccess {Long} version 版本
     * @apiSuccess {Long} mallId 平台ID
     * @apiSuccess {Long} title 标题
     * @apiSuccess {Integer} url 页面链接
     * @apiSuccess {String} pic 专题图片
     * @apiSuccess {String} description 专题描述
     * @apiSuccess {String} backgroundPath 专题背景图片
     * @apiSuccess {String} seqNo 序号(排序字段)
     *
     * @apiSuccessExample {json} Success-Response:
     * {
     *  "code": "1",
     *  "desc": "成功",
     *  "data": [
     *            {
     *             "id": 2,
     *             "dateCreated": "2016-09-02 11:03:48",
     *             "lastUpdated": "2016-09-02 11:03:48",
     *             "version": 0,
     *             "intro": "asd",
     *             "logoPath": "/20160902/201609021103335XJdg7mi.jpg",
     *             "mallId": 2,
     *             "seqNo": 1,
     *             "title": "asd",
     *             "type": "HOMEPAGE"
     *           }
     *        ]
     *  }
     */
    @RequestMapping(value = Routes.MALL_LIST_THEMES, method = RequestMethod.GET)
    @ResponseBody
    public JsonResult listThemes(HttpServletRequest request,TopicDto topicDto) {
        RestDoing doing = jr -> {
            CustomerDto customerDto = customerHelper.getSession(request);
            if (topicDto.getPageNo() == null || topicDto.getPageSize() == null){
                jr.remind("请输入分页条件",log);
                return;
            }
            PageResult<TopicDto> topicPage = topicRepository.findTopicPage(customerDto.getMallId(),topicDto.getId(),this.getPage(topicDto.getPageNo(),topicDto.getPageSize()));
            jr.setData(topicPage);
        };
        return doing.go(request, log);
    }

    /**
     *
     * @api {get} /api/v2/mall/themes_product 专题产品列表
     * @apiGroup mall
     * @apiVersion 1.0.0
     *
     * @apiParam {Integer} pageNo 页码
     * @apiParam {Integer} pageSize 页记录数
     * @apiParam {Long} id 专题Id
     *
     * @apiSuccess {Long} id ID
     * @apiSuccess {Date} dateCreated 创建时间
     * @apiSuccess {Date} lastUpdated 更新时间
     * @apiSuccessExample {json} Success-Response:
     * {
     *  "code":  "1",
     *  "desc": "成功",
     *  "data": {
     *              "data": [
     *                          {
     *                              "id": 1109,
     *                              "dateCreated": "2016-11-24 10:39:08",
     *                              "lastUpdated": "2016-11-23 19:57:28",
     *                              "version": 2,
     *                              "marketId": 1103,
     *                              "marketMallId": 1,
     *                              "marketMerchantId": 74,
     *                              "marketMerchantName": "改名了6666",
     *                              "name": "1123服务001",
     *                              "type": "SERVICE",
     *                              "basePrice": 125,
     *                              "sellPrice": 100,
     *                              "quantity": 10,
     *                              "carriage": 0,
     *                              "dateEnabled": "2016-11-23 00:00:00",
     *                              "dateDisabled": "2016-12-23 00:00:00",
     *                              "refundable": true,
     *                              "barcode": "123456",
     *                              "sellnow": false,
     *                              "dateSelling": "2016-11-23 19:53:30",
     *                              "limitCount": 0,
     *                              "logoUrl": "http://uploads.rockcent.com//uat/product/face/201611/23195126950ef2d800c-b2ab-4228-a414-729b7e6096ed5243fbf2b2119313e3f2c41261380cd790238dda.jpg",
     *                              "logoUrls": "[\"http://uploads.rockcent.com//uat/product/face/201611/23195126950ef2d800c-b2ab-4228-a414-729b7e6096ed5243fbf2b2119313e3f2c41261380cd790238dda.jpg\"]",
     *                              "note": "222222222",
     *                              "status": "SELLING",
     *                              "mallId": 1,
     *                              "merchantId": 1,
     *                              "merchantName": "秋甜商城",
     *                              "serveRate": "5",
     *                              "shippingType": "SHOP_PICKUP",
     *                              "resellFee": 12,
     *                              "shareFee": 10,
     *                              "marketPlatformType": "IN_PLATFORM",
     *                              "productMerchantStoreType": "ALL",
     *                              "recommend": true
     *                          },
     *                          ...
     *                      ],
     *                      "totalCount": 0,
     *                      "totalPage": 0,
     *                      "pageNo": 0,
     *                      "pageSize": 10
     *          }
     *  }
     */
    @RequestMapping(value = Routes.MALL_THEMES_PRODUCT, method = RequestMethod.GET)
    @ResponseBody
    public JsonResult themesDetail(HttpServletRequest request,TopicDto topicDto) {
        RestDoing doing = jr -> {
            if (topicDto.getPageNo() == null || topicDto.getPageSize() == null){
                jr.remind("请输入分页条件",log);
                return;
            }
            if (topicDto.getId() == null){
                jr.remind(" id is null",log);
                return;
            }
            CustomerDto customerDto = customerHelper.getSession(request);
            Topic existTopic = topicRepository.findByIdAndMallIdAndIsDelete(topicDto.getId(),customerDto.getMallId(),Whether.NO);
            if (existTopic == null){
                jr.remind("该主题已不存在",log);
                return;
            }
            PageResult<Product> productPage = merchantProductRepository.findProductByTopicIdPage(topicDto.getId(),this.getPage(topicDto.getPageNo(),topicDto.getPageSize()));
            jr.setData(productPage);
        };
        return doing.go(request, log);
    }

    /**
     *
     * @api {get} /api/v2/mall/wechat_appid 平台 微信配置appid信息
     * @apiGroup mall
     * @apiVersion 1.0.0
     *
     * @apiParam {String} mobileHostName 域名
     *
     * @apiSuccess {String} appId APPID
     * @apiSuccessExample {json} Success-Response:
     * {
     *  "code": "1",
     *  "desc": "成功",
     *  "data": {
     *              "version": 0,
     *              "appid": "I1111"
     *          }
     * }
     *
     */
    @RequestMapping(value = Routes.MALL_WECHAT_APPID, method = RequestMethod.GET)
    @ResponseBody
    public JsonResult wechatAppId(Mall mall, HttpServletRequest request) {
        RestDoing doing = jr -> {
            if (null == mall.getMobileHostName()) {
                jr.errorParam("域名不能为空",log);
                return;
            }
            Mall exitMall = mallRepository.findByMobileHostName(mall.getMobileHostName());
            if (null == exitMall) {
                jr.errorParam("该域名不存在：" + mall.getMobileHostName(),log);
                return;
            }
            MallWechatConfig mallWechatConfig = wechatConfigRepository.findByMallId(exitMall.getId());
            if (null == mallWechatConfig || null == mallWechatConfig.getAppid()) {
                jr.errorParam(Mall.REMIND_RECORD_IS_NOT_EXIST,log);
                return;
            }
            MallWechatConfig ourputMallWechatConfig = new MallWechatConfig();
            ourputMallWechatConfig.setAppid(mallWechatConfig.getAppid());
            jr.setData(ourputMallWechatConfig);
        };
        return doing.go(request, log);
    }

    /**
     *
     * @api {get} /api/v2/mall/show 查询商城信息
     * @apiGroup mall
     * @apiVersion 1.0.0
     *
     * @apiSuccess {Long} id ID
     * @apiSuccess {Date} dateCreated 创建时间
     * @apiSuccess {Date} lastUpdated 更新时间
     * @apiSuccess {Long} version 版本
     * @apiSuccess {String} name APPID
     * @apiSuccess {String} hostname 配置的域名地址
     * @apiSuccess {Long} userInfoId 用户id
     * @apiSuccess {String} serveRate 服务费比率
     * @apiSuccess {String} shareRate 分享返利比率
     * @apiSuccess {String} companyName 公司名称
     * @apiSuccess {String} salesCode 分销码
     * @apiSuccess {String} mobileHostName 手机端域名
     * @apiSuccess {String} customerBusinessDomain 自定义B端域名
     * @apiSuccess {String} customerPlatformDomain 自定义M端域名
     * @apiSuccess {String} customerClientDomain 自定义C端域名
     * @apiSuccess {String} customerDomain 自定义一级域名
     *
     * @apiSuccessExample {json} Success-Response:
     *
     *   {
     *      "code": "1",
     *      "desc": "成功",
     *      "data": {
     *                  "id": 1,
     *                  "dateCreated": "2016-05-06 17:30:29",
     *                  "lastUpdated": "2016-10-21 14:29:39",
     *                  "version": 62,
     *                  "name": "B123aab",
     *                  "hostname": "b1.b.dev.rockcent.com",
     *                  "userInfoId": 2,
     *                  "serveRate": "24",
     *                  "shareRate": "50",
     *                  "salesCode": "M@rlrSX6hR",
     *                  "mobileHostName": "b1.b.dev.rockcent.com",
     *                  "prodAudit": true
     *              }
     *  }
     */
    @RequestMapping(value = Routes.MALL_SHOW , method = RequestMethod.GET)
    @ResponseBody
    public JsonResult show(HttpServletRequest request) {
        CustomerDto customerDto = customerHelper.getSession(request);
        RestDoing doing = jr -> {
            Mall mall =  mallRepository.findOne(customerDto.getMallId());
            jr.setData(mall);
        };
        return doing.go(request, log);
    }
    /**
     *
     * @api {get} /api/v2/mall/get_categories 查询某商城下分类列表(查某分类下子分类)
     * @apiGroup mall
     * @apiVersion 1.0.0
     *
     * @apiParam {Long} categoryId 一级类目ID
     *
     * @apiSuccess {Long} id ID
     * @apiSuccess {Date} dateCreated 创建时间
     * @apiSuccess {Date} lastUpdated 更新时间
     * @apiSuccess {Long} version 版本
     * @apiSuccess {String} name 名称
     * @apiSuccess {String} iconUrl 图标Url
     * @apiSuccess {Boolean} visible 是否可见
     * @apiSuccess {Long} displayOrderId 显示顺序
     * @apiSuccess {String} note 描述
     * @apiSuccess {Long} mallId
     * @apiSuccess {Long} parentId
     *
     * @apiSuccessExample {json} Success-Response:
     *{
     *  "code": "1",
     *  "desc": "成功",
     *  "data": [
     *              {
     *                  "id": 296,
     *                  "dateCreated": "2016-09-28 15:50:49",
     *                  "lastUpdated": "2016-10-21 18:34:35",
     *                  "version": 0,
     *                  "name": "测试类目1",
     *                  "iconUrl": "http://localhost:9090/pic/2016030102.ico",
     *                  "visible": true,
     *                  "displayOrderId": 0,
     *                  "mallId": 1,
     *                  "parentId": 1
     *              },
     *                   ...
     *          ]
     *  }
     */
    @RequestMapping(value = Routes.MALL_GET_CATEGORIES , method = RequestMethod.GET)
    @ResponseBody
    public JsonResult getCategories(Long categoryId, HttpServletRequest request) {
        CustomerDto customerDto = customerHelper.getSession(request);
        RestDoing doing = jr -> {
            //如果categoryId为null时，查的是根分类
            if (null!= categoryId && null == categoryRepository.findByIdAndVisible(categoryId,true)){
                jr.errorParam("无此分类",log);
                return;
            }

            //查下级分类
            List<MallCategoryDto> mallCategoryDtoList = categoryRepository.findVisiableTwoLevel(customerDto.getMallId(),categoryId);

            //查询下下级分类
            List<MallCategoryDto> categoryThreeList = categoryRepository.findVisiableThreeLevel(customerDto.getMallId(),categoryId);
            //按父级分组
            Map<Long, List<MallCategoryDto>> map = categoryThreeList.stream().collect(Collectors.groupingBy(MallCategoryDto::getParentId));

            mallCategoryDtoList = mallCategoryDtoList.stream().map(mallCategoryDto -> {
                   List<MallCategoryDto> list = map.get(mallCategoryDto.getId());
                   if(list != null && list.size() >0 ){
                       mallCategoryDto.setCategoryDtoList(list);
                   }else {
                       mallCategoryDto = null;
                   }
                   return mallCategoryDto;
            }).collect(Collectors.toList());
            mallCategoryDtoList = mallCategoryDtoList.stream().filter(mallCategoryDto -> mallCategoryDto != null).collect(Collectors.toList());
            jr.setData(mallCategoryDtoList);
        };
        return doing.go(request, log);
    }
    /**
     *
     * @api {get} /api/v2/mall/get_root_categories 查询某商城下所有根分类列表
     * @apiGroup mall
     * @apiVersion 1.0.0
     *
     * @apiParam {Long} mallId 商城ID
     *
     * @apiSuccess {Long} id ID
     * @apiSuccess {Date} dateCreated 创建时间
     * @apiSuccess {Date} lastUpdated 更新时间
     * @apiSuccess {Long} version 版本
     * @apiSuccess {String} name 名称
     * @apiSuccess {String} iconUrl 图标Url
     * @apiSuccess {Boolean} visible 是否可见
     * @apiSuccess {Long} displayOrderId 显示顺序
     * @apiSuccess {String} note 描述
     * @apiSuccess {Long} mallId
     * @apiSuccess {Long} parentId
     *
     * @apiSuccessExample {json} Success-Response:
     *{
     *  "code": "1",
     *  "desc": "成功",
     *  "data": [
     *              {
     *                  "id": 296,
     *                  "dateCreated": "2016-09-28 15:50:49",
     *                  "lastUpdated": "2016-10-21 18:34:35",
     *                  "version": 0,
     *                  "name": "测试类目1",
     *                  "iconUrl": "http://localhost:9090/pic/2016030102.ico",
     *                  "visible": true,
     *                  "displayOrderId": 0,
     *                  "mallId": 1,
     *                  "parentId": 1
     *              },
     *                   ...
     *          ]
     *  }
     */
    @RequestMapping(value = Routes.MALL_GET_RROOT_CATEGORIES , method = RequestMethod.GET)
    @ResponseBody
    public JsonResult getRootCategories(HttpServletRequest request) {
        CustomerDto customerDto = customerHelper.getSession(request);
        RestDoing doing = jr -> {
            //一级类目（根）
            List<Category> categoryList = categoryRepository.findMallCategories(customerDto.getMallId());
            List<Long> categoryIdList = categoryList.stream().map(Category::getId).collect(Collectors.toList());
            //二级类目
            List<Category> child = categoryRepository.findByMallIdAndVisibleAndIsDeleteAndParentIdIn(customerDto.getMallId(),Boolean.TRUE,Whether.NO,categoryIdList);
            Map<Long,List<Category>> childParentIdMap = child.stream().collect(Collectors.groupingBy(Category::getParentId));
            //二级类目为空时，一级类目不显示
            categoryList = categoryList.stream().filter(category -> childParentIdMap.get(category.getId())!= null && childParentIdMap.get(category.getId()).size()>0).collect(Collectors.toList());
            jr.setData(categoryList);
        };
        return doing.go(request, log);
    }

    /**
     *
     * @api {get} /api/v2/mall/get_advising 推荐商品
     * @apiGroup mall
     * @apiVersion 1.0.0
     *
     * @apiParam {Integer} pageNo 页码
     * @apiParam {Integer} pageSize 页记录数
     *
     * @apiSuccess {Long} id 产品ID
     * @apiSuccess {Date} dateCreated 创建时间
     * @apiSuccess {Date} lastUpdated 更新时间
     * @apiSuccess {String} name 名称
     * @apiSuccess {BigDecimal} basePrice 原价
     * @apiSuccess {BigDecimal} sellPrice 售价
     * @apiSuccess {Long} quantity  库存数量
     * @apiSuccess {Boolean} refundable 是否支持过期退
     * @apiSuccess {Boolean} sellnow 是否立即开售
     * @apiSuccess {Date} dateSelling 开售时间
     * @apiSuccess {Long} limitCount 限购数量
     * @apiSuccess {String} logoUrl LOGO图
     * @apiSuccess {String} logoUrls 多LOGO图
     * @apiSuccess {String} note 卖点介绍
     * @apiSuccess {String} status 状态 SELLING("在售"), SUPPLIER_CANCEL_SOLDOUT("分销市场 供应商取消供货 已下架"),DISTRIBUTOR_CANCEL_SOLDOUT("分销市场 分销商取消代销 已下架"), SOLDOUT("已下架"), EXPIRED("已过期"), DELETED("已删除"), WAIT_APPLY("待申请"), WAIT_AUDIT("待审核"), AUDIT_PASS("审核通过"), AUDIT_FAIL("审核不通过")
     * @apiSuccess {Long} mallId 平台ID
     * @apiSuccess {Long} merchantId 商家ID
     * @apiSuccess {String} serveRate 服务费比率
     * @apiSuccess {String} shippingType 支持的物流类型 SHOP_PICKUP("到店自取"), SHIPPING("物流"), SHOP_PICKUP_AND_SHIPPING("物流及到店自取")
     * @apiSuccess {BigDecimal} resellFee 分销佣金
     * @apiSuccess {BigDecimal} shareFee 分享返利
     * @apiSuccess {Integer} totalCount 总记录数
     * @apiSuccess {Integer} totalPage 总页数
     * @apiSuccess {Integer} pageNo 页码
     * @apiSuccess {Integer} pageSize 每页记录数
     *
     * @apiSuccessExample {json} Success-Response:
     *{
     *  "code": "1",
     *  "desc": "成功",
     *  "data": {
     *          "data": [
     *                      {
     *                          "id": 7,
     *                          "dateCreated": "2016-05-06 13:58:42",
     *                          "lastUpdated": "2016-10-26 17:31:13",
     *                          "version": 40,
     *                          "name": "婚纱",
     *                          "type": "GOODS",
     *                          "basePrice": 10000,
     *                          "sellPrice": 0.01,
     *                          "quantity": 89,
     *                          "carriage": 0,
     *                          "refundable": false,
     *                          "sellnow": true,
     *                          "dateSelling": "2016-05-06 13:58:42",
     *                          "limitCount": 0,
     *                          "logoUrl": "/20160506/20160506135926ztRTRuRb.jpg",
     *                          "note": "买婚纱送头饰",
     *                          "status": "SOLDOUT",
     *                          "mallId": 1,
     *                          "merchantId": 2,
     *                          "serveRate": "2.5",
     *                          "resellFee": 0.05,
     *                          "shareFee": 0.04,
     *                          "recommend": false
     *                      },
     *                       ...
     *                  ],
     *                  "totalCount": 10,
     *                  "totalPage": 1,
     *                  "pageNo": 0,
     *                  "pageSize": 10
     *      }
     *  }
     */
    @RequestMapping(value = Routes.MALL_GET_ADVISING , method = RequestMethod.GET)
    @ResponseBody
    public JsonResult getAdvising(Integer pageNo,Integer pageSize ,HttpServletRequest request) {
        CustomerDto customerDto = customerHelper.getSession(request);
        RestDoing doing = jr -> {
            if (pageNo == null || pageSize == null) {
                jr.remind("请输入分页条件",log);
                return;
            }
            //限制只能显示100条信息
            if ((pageNo + 1) * pageSize > 100) {
                jr.setData("[]");
                return;
            }
            PageResult<Product> productPageResult = null;
            productPageResult = mallService.getAdvising(pageNo, pageSize, customerDto);
            jr.setData(productPageResult);
        };
        return doing.go(request, log);
    }

    /**
     *
     * @api {get} /api/v2/mall/protocols_info 协议管理详情
     * @apiGroup MALL_PROTOCOLS
     * @apiVersion 1.0.0
     * @apiHeader {String} userToken 用户token
     * @apiHeader {String} domain 请求域名
     *
     * @apiParam {String} protocolType 协议类型 <code>必传参数</code> 传值CUSTOMER_PROTOCOL
     *
     * @apiSuccessExample {json} Success-Response:
     * {"
     * code":"1",
     * "desc":"成功",
     * "data":[
     *  {
     *    "id":1,
     *    "title":"管理列表",
     *    "lastUpdated":"2016-11-15 14:38:35",
     *    "content":"为空表示查询顶级分类列表，不为空表示该parentId下的子分类列表",
     *    "versionNo": 1,
     *    "protocolType":""
     *  }
     * ]
     * }
     */
    @RequestMapping(value = Routes.MALL_PROTOCOLS_INFO, method = RequestMethod.GET)
    public JsonResult protocolsInfo(HttpServletRequest request, MallProtocolDto dto) {
        CustomerDto customerDto = customerHelper.getSession(request);
        RestDoing doing = jsonResult -> {
            if (StringUtils.isBlank(dto.getProtocolType()) || !EnumUtils.isValidEnum(ProtocolType.class, dto.getProtocolType())) {
                jsonResult.remind("CUSTOMER_PROTOCOL(\"用户服务协议\")",log);
                return;
            }
            MallProtocol mallProtocol = mallProtocolRepository.findByMallIdAndExpireAndProtocolTypeAndIsDelete(customerDto.getMallId(), Whether.NO, ProtocolType.valueOf(dto.getProtocolType()), Whether.NO);
            jsonResult.data = mallProtocol;
        };
        return doing.go(request, log);
    }
}
